<?php
/**
 * wechat php test
 */

//define your token
define("TOKEN", "weixin");
$wechatObj = new wechatCallbackapiTest();
$wechatObj->valid();
$wechatObj->responseMsg();

class wechatCallbackapiTest
{
	public function valid()
	{
		$echoStr = $_GET["echostr"];

		//valid signature , option
		if($this->checkSignature()){
			echo $echoStr;
		}
	}

	public function responseMsg()
	{
		//get post data, May be due to the different environments
		$postStr = $GLOBALS["HTTP_RAW_POST_DATA"];

		//extract post data
		if (!empty($postStr)){

			$postObj = simplexml_load_string($postStr, 'SimpleXMLElement', LIBXML_NOCDATA);
			$fromUsername = $postObj->FromUserName;
			$toUsername = $postObj->ToUserName;
			$keyword = trim($postObj->Content);
			$time = time();
			$textTpl = "<xml>
				<ToUserName><![CDATA[%s]]></ToUserName>
				<FromUserName><![CDATA[%s]]></FromUserName>
				<CreateTime>%s</CreateTime>
				<MsgType><![CDATA[%s]]></MsgType>
				<Content><![CDATA[%s]]></Content>
				<FuncFlag>0</FuncFlag>
				</xml>";
			if(!empty( $keyword ))
			{
				ob_start();
				error_reporting(0);
				$msgType = "text";
				echo sprintf($textTpl, $fromUsername, $toUsername, $time, $msgType, '查询超时！');

				set_time_limit(2);
				$contentStr  = $this->parse_command($keyword);
				$contentStr .= "\n输入?获取帮助";
				$resultStr = sprintf($textTpl, $fromUsername, $toUsername, 
						$time, $msgType, $contentStr);
				ob_clean();
				echo $resultStr;
			}else{
				echo "Input something...";
			}
		}else {
			echo "";
			exit;
		}
	}

	private function checkSignature()
	{
		$signature = $_GET["signature"];
		$timestamp = $_GET["timestamp"];
		$nonce = $_GET["nonce"];

		$token = TOKEN;
		$tmpArr = array($token, $timestamp, $nonce);
		sort($tmpArr);
		$tmpStr = implode( $tmpArr );
		$tmpStr = sha1( $tmpStr );

		if( $tmpStr == $signature ){
			return true;
		}else{
			return false;
		}
	}


	public function usage()
	{
		$usage  = "使用方法：\n";
		$usage .= "1、站台名：查过站公交位置\n";
		$usage .= "2、站台名 公交路数：查指定公交位置\n";
		$usage .= "3、站台编号 公交路数：查指定公交位置\n";
		$usage .= "4、ye 卡号：查询公交卡余额\n";
		return $usage;
	}
	public function parse_command($command)
	{
		$cmd = explode(' ',trim($command));

		switch(count($cmd)) {
			case 2:
				//查询余额
				if ($cmd[0]=='ye') {
					$result = $this->get_ye($cmd[1]);
				} else {
					$result = $this->get_by_station_busnum($cmd[0], $cmd[1]);
				}
				break;
			case 1:
				if ($cmd[0]=='?' || $cmd[0]=='？') {
					$result = $this->usage();
				} else if (!is_numeric($cmd[0])) {
					$result = $this->get_by_station_busnum($cmd[0], '');
				} else {
					$result = $this->usage();
				}
				break;
			default:
				$result = $this->usage();
				break;
		}
		return $result;
	}

	public function get_ye($card_num)
	{
		$url  = 'http://www.10628106.com/ADSB/CardBalance.aspx';
		$url .= "?CardNum={$card_num}";
		$response = $this->send_request($url);

		$response  = strstr($response, '<div style="margin-left: 15px');
		$response  = strstr($response, '<br />',true);
		$response  = trim(strip_tags($response));
		$mix = explode(' ', $response);
		$response  = $mix[0];
		unset($mix[0]);
		$response .= ' '.implode("\n",$mix);
		if ($response == ' ') {
			$response = "卡号[{$card_num}]错误！";
		}
		return $response;
	}

	public function get_by_station_busnum($station, $busnum='')
	{
		$fix_station = $station;
		if (!is_numeric($station) && mb_substr($station,-3,3)!='站') {
			$fix_station .= '站';
		}
		$url  = 'http://www.10628106.com/ADSB/BusLocation.aspx';
		$url .= "?GpsSite={$fix_station}&busNum={$busnum}";
		$response = $this->send_request($url);
		$response = strstr($response, '<div style="margin: 5px 0px 5px 10px;">');
		$response = strstr($response, '</div>',true);
		$response = str_replace('<br />', "\n", $response);
		$response = trim(strip_tags($response));
		$response = str_replace("\n请保管好个人物品，不要携带危险品。",'', $response);
		if (is_numeric($station)) {
			$response = substr($response, strpos($response, ')')+1);
		} else {
			$response = str_replace("距离{$station}",'', $response);
		}
		return $response;
	}

	public function send_request($uri)
	{
		$options = array(
				CURLOPT_HEADER => 0,
				CURLOPT_URL => $uri,
				CURLOPT_COOKIEJAR => '/tmp/weixin_cookie.txt',
				CURLOPT_RETURNTRANSFER => true,
				);
		$ch = curl_init();
		curl_setopt_array($ch, $options);
		$response = curl_exec($ch);
		return $response;
	}
}

?>
